





var domain=document.domain

  
var canva;
var idcanvar;

function setup() {
    // 800 x 400 (double width to make room for each "sub-canvas")
    var combin =createCanvas(900, 600);
    var notice = createDiv([p]='点击查看最新的用户词语').position(900,700,)
    createDiv([p]='点击查看最新的用户问题').position(400,700)
    
    // Create both of your off-screen graphics buffers
    canva = createGraphics(400, 300);
    drawData();
    var button = select('#submit');
    button.mousePressed(submitWord);

    idcanvar=  createGraphics(400, 300);
    
    var submiBut = select('#useraccess');
    submiBut.mousePressed(submitID);
    drawDataID();
    drawLatestQ()
    
 

}
function drawLatestQ(){
  $.ajax({
    type:'GET',
    url:'/latestquestions',
    contentType: "application/json",
    success: function(){console.log('请求最新问题')
    },
    }).then((res)=>{
      latestqs=(JSON.stringify(res))
      latestQfinished(latestqs)
    })
}
function latestQfinished(latestqs){
  for (someoneq in JSON.parse(latestqs)){
  console.log(someoneq.questions['编辑好的主观题'])

  }
 
  
}
// setup.then(( function(){
//   for (elp in ellipse){
//     elp.mouseOver(alert(elp[2]))     
//    }
//   })()
//     )



function submitWord() {
  var word = select('#word').value();
  var score = select('#score').value();
  console.log(word, score);

  $.ajax({
    type:'GET',
    url:'/add/'+ word +'/'+score,
    
    success: function(){console.log('上传请求已发送')
    },
    }).then((res)=>{
      alert(JSON.stringify(res)+`\n`+"上传成功")
      finished
    })
;

  function finished(data) {
    console.log(data);
    drawData();
  }
}

function drawData() {
  loadJSON('all', gotData);

}




function submitID() {
  var logincheck =document.getElementById('toLogin')
  
var id =document.getElementById('name').value
var password =document.getElementById('password').value
console.log(id)
console.log(password)
let date_ob = new Date();

let date = ("0" + date_ob.getDate()).slice(-2);

let hours = date_ob.getHours();

let minutes = date_ob.getMinutes();

var timeob =(date + " " + hours + ":" + minutes  );

 var time =timeob.toString()
    var body = JSON.stringify({
      "name": `${id}`, "password": `${password}`, "loginTime":time
            })
    console.log(body)
   if (logincheck.value =="toLogin"){
    $.ajax({
      type:'POST',
      url: '/users/login',
      contentType: "application/json",
      data: body,
      success: function(){console.log('请求登录发送 SUCCESS')
      },
    }).then((res)=>{
      console.log(res)
      localStorage.removeItem('currentUSER')
      localStorage.setItem('currentUSER', id)
      console.log(localStorage.getItem('currentUSER'))
   
    }

  

  
   )
  } 
  else if(logincheck.value=="toRegister"){ 
    $.ajax({
      type:'GET',
      url:domain+'/users',
      contentType: "application/json",
      success: function(){console.log('请求用户库成功Request Sent SUCCESS')},

    }).then((res)=>{
      
      if ( res.includes(id)){
        alert('用户名不可用')
        
      }
      else{console.log(res)
        var poopconfir = window.prompt('请确认密码，确认后不可更改')
     console.log(poopconfir.toString())
     if (password = poopconfir.toString()){
    var body = JSON.stringify({
      "name": `${id}`, "password": `${password}`
            })  
    console.log(body)
    $.ajax({
    type:'POST',
    url:domain+'/users',
    contentType: "application/json",
   
    data:  body,
    success: function(){console.log('Post SUCCESS')},

    error: function(){alert('本地发送失败')}
  }).then((res)=>{alert(res)})


      }
     }
    })
     
  
  // let h = new Headers()
  //     h.append('Accept','application/json')
  //   const options={
  //     method: 'POST',
  //     body:             {
  //                   "name": `${id}`, "password": `${password}`
  //                        },
  //     header: h,
  //     mode: 'cors',
  //   } 


  //   fetch('http://localhost:3000/users',options) .catch((err) =>{console.log(err.message)})
      
  //   ;
    
  //   success: function(newAcc){
  //     console.log(newAcc)
  //     alert('注册成功')
  //   },
  //   error: function(){alert('error')}

  // })

  


}
}

function drawDataID(){
  loadJSON('allid', gotaccessid);
}

var ellipse =[]
var distance =[]
var keys
function gotData(data) {

   keys= Object.keys(data);

canva.background(255, 255, 100);

canva.textSize(26);  
var h = 0;
var j =0;
while(  j<keys.length){
  while(h<5){  
  for(k=0;k<5;k++){
    var word = keys[j];
    var score = data[word];
    var xpose = 10 + k*80
    var ypose = 20 +h*60     
    canva.ellipse( xpose, ypose,10,10)   
      background(100);
      ellipse[j] = []
      ellipse[j][0]= 400 +xpose
      ellipse[j][1]= 200 +ypose
      ellipse[j][2]=keys[j]
   console.log(ellipse[j])
  ;j++
}h++;
}j++;
console.log('第'+j)
}
image(canva, 400, 200);}



function mousePressed() {
  for (j=0;j<ellipse.length;j++){
    console.log(mouseX,mouseY)
   distance[j] = dist(mouseX, mouseY, ellipse[j][0], ellipse[j][1]);
   if (distance[j] < 20) {
     // Pick new random color values
     alert(keys[j])
   }
 }
 }


function gotaccessid(data){
  
  // var name =document.getElementById('#name').value
  // var emial = document.getElementById('#email').value
  // var accessid = useraccessID
 

  var keys = Object.keys(data);

  idcanvar.background(255, 100, 255);
 
 
  idcanvar.textSize(26);
  var i
  function ivalue () {return i =(j+1)/5};
  var h = 0
    for( var j =0; j<keys.length; j++){
    var id = keys[j];
    var time = data[id];
    var xpose = 10 + j*80 
    var ypose = 40 +h*60
    ivalue()
    if (i -h > 1 )
    {h++
      console.log('j=5')
      while(  j< keys.length ){
    var id = keys[j];
    var time = data[id];
    var xpose = 10 + (j-5)*80 
    var ypose = 20 +h*60
    idcanvar.ellipse( xpose, ypose,10,10) 
    j++;
    if (j>= keys.length){break}
    ivalue()
     if (i -h>1){
       h++
        while(  j<keys.length){
       
      var id = keys[j];
      var time = data[id];
      var xpose = 10 + (j-10)*80 
      var ypose = 20 +h*60
      idcanvar.ellipse( xpose, ypose,10,10) 
      j++;
      if (j>= keys.length){break}
      ivalue()
      if ( i- h > 1){ alert ('数据过多')
      if (j>= keys.length){break}
      break
      
     } 
    }
    }
    
     
    }
    }
    idcanvar.ellipse( xpose, ypose,10,10) 
    }
  image(idcanvar, 0,200);
}

 

// var socket;

// function setup() {
//   createCanvas(400, 400);
//   background(0);
//   // Start a socket connection to the server
//   // Some day we would run this server somewhere else
//   socket = io.connect('http://localhost:3000');
//   // We make a named event called 'mouse' and write an
//   // anonymous callback function
//   socket.on('mouse',
//     // When we receive data
//     function(data) {
//       console.log("Got: " + data.x + " " + data.y);
//       // Draw a blue circle
//       fill(0,0,255);
//       noStroke();
//       ellipse(data.x, data.y, 20, 20);
//     }
//   );
// }

// function draw() {
// }

// function mouseDragged() {
//   // Draw some white circles
//   fill(255);
//   noStroke();
//   ellipse(mouseX,mouseY,20,20);
//   // Send the mouse coordinates
//   sendmouse(mouseX,mouseY);
// }

// // Function for sending to the socket
// function sendmouse(xpos, ypos) {
//   // We are sending!
//   console.log("sendmouse: " + xpos + " " + ypos);
  
//   // Make a little object with  and y
//   var data = {
//     x: xpos,
//     y: ypos
//   };

//   // Send that object to the socket
//   socket.emit('mouse',data);
// }
